package com.xuzz.study.io.netty.protocoltcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.util.UUID;

public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol msg) throws Exception {
        /*byte[] buffer = new byte[msg.readableBytes()];
        msg.readBytes(buffer);

        String message = new String(buffer, Charset.forName("utf-8"));
        System.out.println("服务器接收到数据 "+message);
        System.out.println("服务器接收到消息量 "+(++this.count));

        ByteBuf byteBuf = Unpooled.copiedBuffer(UUID.randomUUID().toString(), Charset.forName("utf-8"));
        channelHandlerContext.writeAndFlush(byteBuf);*/

        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println();
        System.out.println();
        System.out.println("服务器接收到信息如下");
        System.out.println("长度="+ len);
        System.out.println("内容="+new String(content,Charset.forName("utf-8")));
        System.out.println("服务器接收到消息包数量="+(++count));

        //回复消息
        String response = UUID.randomUUID().toString();
        byte[] bytes = response.getBytes(Charset.forName("utf-8"));
        int responseLen = bytes.length;

        MessageProtocol responseMessageProtocol = new MessageProtocol();
        responseMessageProtocol.setLen(responseLen);
        responseMessageProtocol.setContent(bytes);
        channelHandlerContext.writeAndFlush(responseMessageProtocol);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
